# -*- coding: utf-8 -*-
# @file    : _base
# @Date    : 2020/11/19
# @Author  :
# @Version : 1.0.0
"""
Miscellaneous tools
"""
import os
import re
import time
import datetime
import functools

from .constant import ROOT_PATH, DEBUG, STATIC_BAK_PATH, DTF
from .log import logger as _logger


def get_abs_path(path):
    """
    获取绝对路径
    :param path: 相对路径
    :return:
    """
    if not os.path.isabs(path):
        path = os.path.join(ROOT_PATH, path)
    return os.path.abspath(path)


def load_file(path):
    """
    读取文件
    :param path: 相对路径
    :return:
    """
    abs_path = get_abs_path(path)
    with open(abs_path, 'rb') as f:
        content = f.read()
        return content


def store_file(path, data):
    """
    存储文件
    :param path:
    :param data:
    :return:
    """
    abs_path = get_abs_path(path)
    if not os.path.exists(os.path.dirname(abs_path)):
        os.makedirs(os.path.dirname(abs_path))
    with open(abs_path, 'wb') as f:
        f.write(data)


def proxy(func, *args, **kwargs):
    """
    代理请求
    :param func:
    :param args:
    :param kwargs:
    :return:
    """
    response = None
    try:
        response = func(*args, **kwargs)
    except Exception as e:
        _logger.warning("请求失败: %s", e)

    return response


def headers2dict(headers):
    """
    响应头转为字典
    :param headers:
    :return:
    """
    d = {}
    for k in headers:
        if k in ("Content-Length", 'Content-Encoding', "Transfer-Encoding"):
            continue
        d[k] = headers.get(k)

    return d


def load_cookie(file_path):
    """
    读取文件中的cookie
    :return:
    """
    content = None
    if not os.path.exists(file_path):
        return content
    try:
        with open(file_path, 'r') as f:
            content = f.read()
    except (OSError, IOError) as e:
        _logger.error(e)

    finally:
        return content


def report_process_time(func):
    """
    报告函数的执行时长
    :param func:
    :return:
    """
    if not DEBUG:
        return func

    @functools.wraps(func)
    def process(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        _logger.info('%s.%s, 执行时间: %s', func.__module__, func.__name__, time.time() - start)
        return result

    return process


def gen_bak_file_name():
    """
    生成备份文件的文件名
    :return:
    """
    dir_path = get_abs_path(STATIC_BAK_PATH)
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

    return os.path.join(dir_path, 'static_backup_%s.zip' % datetime.datetime.now().strftime(DTF))


def read_update_info(content):
    """
    从文本中读取更新信息
    :param content:
    :return:
    """
    text = content.replace('\r\n', '\n').replace('\r', '\n')
    lines = text.split('\n')

    if len(lines) >= 4:
        date = re.search(r'\d{4}-\d{2}-\d{2}', lines[2])
        date = date.group() if date else ''
        uuid = re.search(r'\w+?-\w+?-\w+?-\w+?-\w+', lines[3])
        uuid = uuid.group() if uuid else ''

    else:
        uuid = ''
        date = ''

    version = "%s(%s)" % (date, uuid) if date and uuid else "未知版本"

    return date, uuid, version
